﻿#include "httpserver.h"
#include <QThread>
#include <QJsonDocument>
#include "qhttp/qhttpserver.hpp"
#include "qhttp/qhttpserverconnection.hpp"
#include "qhttp/qhttpserverrequest.hpp"
#include "qhttp/qhttpserverresponse.hpp"
#include "common_log.h"
#include "http_log.h"
#include "json_trans.h"


HttpServer::HttpServer(QObject* parent)
	: QObject(parent)
{
	m_http = new qhttp::server::QHttpServer();
	m_th = new QThread();
	//this->moveToThread(m_th);
	//m_th->start();
}

HttpServer::~HttpServer()
{
	m_http->deleteLater();
	m_th->deleteLater();
}
int HttpServer::StartSever(const QString& ip, int port)
{

	if (ip.isEmpty() || port <= 0) {
		return -1;
	}
	m_ip = ip;
	m_port = port;
	log_info("param ip [{}], prot:[{}]", m_ip, m_port);
	bool ret = m_http->listen(QHostAddress::Any, m_port);
	if (!ret) {
		return -2;
	} else {
		connect(m_http, &qhttp::server::QHttpServer::newRequest, this, &HttpServer::DealWitHttpInfo);
		/*connect(m_http, &qhttp::server::QHttpServer::newConnection, [&]() {
			log_trace("new connect");
			});*/
	}

	return 0;
}

int HttpServer::ReStartSever()
{
	if (!m_http->isListening()) {
		m_http->listen(QHostAddress(m_ip), m_port, [&](qhttp::server::QHttpRequest* req, qhttp::server::QHttpResponse* rep) {
			DealWitHttpInfo(req, rep);
			});
	}
	if (!m_http->isListening()) {
		log_error("Server start error, maybe param error");
		return -2;
	}
	return 0;
}

bool HttpServer::IsListening()
{
	return m_http->isListening();
}

bool HttpServer::RegisterServerFunc(ServerFun fun)
{
	if (fun == nullptr) {
		return false;
	}
	m_callBack = fun;
	return true;
}

void HttpServer::DealWitHttpInfo(qhttp::server::QHttpRequest* req, qhttp::server::QHttpResponse* rep)
{
	rep->addHeader("Access-Control-Allow-Origin", "*");
	// res->addHeader("Access-Control-Allow-Origin", "http://localhost:8080");
	rep->addHeader("Access-Control-Allow-Headers", "*");
	req->collectData();
	req->onEnd([&, req, rep]() {
		ParseHttpdata(req, rep);
		});
}

void HttpServer::ParseHttpdata(qhttp::server::QHttpRequest* req, qhttp::server::QHttpResponse* rep)
{
	rep->setStatusCode(qhttp::TStatusCode::ESTATUS_OK);
	QString path = req->url().path();
	wcs_info("path: {}", path.toLocal8Bit());
	QByteArray ansData{};
	QByteArray reqData = req->collectedData();
	wcs_info("data: {}", reqData);
	(m_callBack)(path, reqData, ansData);
	wcs_info("Ans: {}", ansData);
	rep->setStatusCode(qhttp::TStatusCode::ESTATUS_OK);
	rep->addHeader("content-Type", "application/json");
	rep->addHeaderValue("content-length", ansData.size());
	rep->end(ansData);
}

